package com.zxy.supplier_system.server.service

import com.zxy.supplier_system.server.entity.WechatUserInfo
import com.zxy.supplier_system.server.repository.WechatUserInfoRepository
import com.zxy.supplier_system.server.utils.LoggerDelegate
import com.zxy.supplier_system.server.utils.wechat.official.BatchGetUserInfoRequest
import com.zxy.supplier_system.server.utils.wechat.official.WechatOfficialAccountHelper
import com.zxy.supplier_system.server.utils.wechat.official.batchGetUserInfo
import jakarta.transaction.Transactional
import org.springframework.stereotype.Service

@Service
class WechatUserInfoService(
    private val wechatUserInfoRepository: WechatUserInfoRepository,
    private val wechatOfficialAccountHelper: WechatOfficialAccountHelper
) {

    companion object{
        private val log by LoggerDelegate()
    }

    @Transactional
    fun fetchAndUpdateOfficialAccountFollowers(followers:List<String>){
        log.info("有{}个关注者",followers.size)
        val followWechatUserInfos = wechatUserInfoRepository.findByOfficialAccountOpenIdIn(followers)
        val followWechatUserInfoOpenIdSet = followWechatUserInfos.map {
            it.officialAccountOpenId
        }.toSet()
        val noDataFollowers = followers.filter {
            !followWechatUserInfoOpenIdSet.contains(it)
        }
        log.info("有{}没有数据的个关注者",noDataFollowers.size)
        if (noDataFollowers.isEmpty()) return
        val body =wechatOfficialAccountHelper.batchGetUserInfo(BatchGetUserInfoRequest(
            noDataFollowers.map {
                BatchGetUserInfoRequest.Item(it)
            }
        ))
        log.info("拉去到{}条关注者信息",body.user_info_list.size)
        val userInfoList = body.user_info_list
        for (user in userInfoList) {
            log.info("用户openId:{} unionId:{}",user.openid,user.unionid)
            if (user.unionid!=null){
                saveFromOfficialAccountOpenIdAndUnionId(user.openid, user.unionid)
            }
        }
    }

    fun saveFromOfficialAccountOpenIdAndUnionId(openId: String,unionId: String): WechatUserInfo {
        val wechatUserInfo = wechatUserInfoRepository.findByUnionId(unionId) ?: WechatUserInfo().apply {
            this.unionId = unionId
        }
        wechatUserInfo.officialAccountOpenId = openId
        this.wechatUserInfoRepository.save(wechatUserInfo)
        return wechatUserInfo
    }

}